package com.zsd.android.common.utils

import android.app.Activity
import android.content.Context
import android.content.pm.PackageManager
import android.os.Build
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import androidx.fragment.app.Fragment
import kotlin.collections.ArrayList

class PermissionHelper private constructor(mContext: Context) {

    private val mContext: Context = mContext

    init {
        MLog.mLog("init")
    }

    /**
     * 单例模式
     */
    companion object Factory {

        @Volatile
        private var instance: PermissionHelper? = null

        fun getInstance(mContext: Context): PermissionHelper? {
            var helper = instance
            if (helper == null) {
                synchronized(PermissionHelper::class) {
                    if (helper == null) {
                        helper = PermissionHelper(mContext)
                        helper = instance
                    }
                }
            }
            return helper
        }
    }

    /**
     * 申请权限
     *
     * @param obj Activity或则Fragment
     * @param permissions 权限数组
     * @param requestCode 申请权限码
     * @return 全部已授权返回true，否则false
     */
    fun isPermission(obj: Any, permissions: Array<String>, requestCode: Int): Boolean {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            var needPermissions = needPermissions(permissions)
            if (needPermissions.size > 0) {
                if (obj is Activity) {
                    ActivityCompat.requestPermissions(
                        obj,
                        needPermissions.toTypedArray(),
                        requestCode
                    )
                } else if (obj is Fragment) {
                    (obj).requestPermissions(needPermissions.toTypedArray(), requestCode)
                }
                return false
            }
            return true
        }
        return true
    }

    /**
     * 抽取没有授权的权限
     *
     * @param permissions 权限数组
     */
    private fun needPermissions(permissions: Array<String>): ArrayList<String> {
        var needPermissions: ArrayList<String> = ArrayList()
        for (permission in permissions) {
            if (PackageManager.PERMISSION_DENIED == ContextCompat.checkSelfPermission(
                    mContext,
                    permission
                )
            ) {
                needPermissions.add(permission)
            }
        }
        return needPermissions
    }
}